/*
 * temperature.cpp
 *
 *  Created on: 23/02/2013
 *      Author: cerber0
 */
#include <temperature.h>

dht DHT11;

//Celsius to Fahrenheit conversion
double temperature::Fahrenheit(double celsius)
{
	return 1.8 * celsius + 32;
}

// fast integer version with rounding
//int Celcius2Fahrenheit(int celcius)
//{
//  return (celsius * 18 + 5)/10 + 32;
//}


//Celsius to Kelvin conversion
double temperature::Kelvin(double celsius)
{
	return celsius + 273.15;
}

// dewPoint function NOAA
// reference: http://wahiduddin.net/calc/density_algorithms.htm
double temperature::dewPoint(double celsius, double humidity)
{
	double A0= 373.15/(273.15 + celsius);
	double SUM = -7.90298 * (A0-1);
	SUM += 5.02808 * log10(A0);
	SUM += -1.3816e-7 * (pow(10, (11.344*(1-1/A0)))-1) ;
	SUM += 8.1328e-3 * (pow(10,(-3.49149*(A0-1)))-1) ;
	SUM += log10(1013.246);
	double VP = pow(10, SUM-3) * humidity;
	double T = log(VP/0.61078);   // temp var
	return (241.88 * T) / (17.558-T);
}

// delta max = 0.6544 wrt dewPoint()
// 5x faster than dewPoint()
// reference: http://en.wikipedia.org/wiki/Dew_point
double temperature::dewPointFast(double celsius, double humidity)
{
	double a = 17.271;
	double b = 237.7;
	double temp = (a * celsius) / (b + celsius) + log(humidity/100);
	double Td = (b * temp) / (a - temp);
	return Td;
}


void temperature::calibration()
{
	int reading;
	soilMin = 1023;
	soilMax = 0;
	// calibrate during the first five seconds
	//Serial.print(millis());
	//Serial.print(" ,\t");
	while (millis() < 10000) {
		reading = analogRead(SOIL_PIN);
		//Serial.print("sensor inicio=> ");
		//Serial.println(reading);
		// record the maximum sensor value
		if (reading > soilMax) {
			soilMax = reading;
		}

		// record the minimum sensor value
		if (reading < soilMin) {
			soilMin = reading;
		}
			//Serial.print(soilMin);
			//Serial.print(" ,\t");
			//Serial.print(soilMax);
			//Serial.print(" ,\t");
	}
}

int temperature::read()
{
	int chk = DHT11.read11(DHT11_PIN);
	int reading = 0;
	int sum = 0;
	for (int i = 0; i <= 4; i++)
	{
		reading = analogRead(SOIL_PIN);
		//Serial.print(reading);
		//Serial.print(" ,\t");
		sum = sum + reading;
	}
	//reading = map(reading, soilMin, soilMax, 0, 255);
	//Serial.print(sum/5);
	//Serial.print(" ,\t");
	soilHumidity = (float) sum*20/1024;

	switch (chk)
	{
	case DHTLIB_OK:
		//Serial.print("OK,\t");
		dewPointD = dewPoint(DHT11.temperature,DHT11.humidity);
		temp = DHT11.temperature;
		humidity = DHT11.humidity;
		break;
	case DHTLIB_ERROR_CHECKSUM:
		//Serial.print("Checksum error,\t");
		break;
	case DHTLIB_ERROR_TIMEOUT:
		//Serial.print("Time out error,\t");
		break;
	default:
		//Serial.print("Unknown error,\t");
		break;
	}
	return chk;
}


